#!/bin/bash

# 日志目录
LOG_DIR="/data/app/we-yan-agent/logs"
mkdir -p $LOG_DIR

# 函数：检测端口是否被监听
is_port_in_use() {
    local port=$1
    if ss -tuln | grep -q ":$port"; then
        return 0  # 占用
    else
        return 1  # 未占用
    fi
}

# 启动 genie-client（1601）
start_client() {
    local port=1601
    if is_port_in_use $port; then
        echo "Port $port is already in use. genie-client may already be running."
    else
        echo "Starting genie-client on port $port..."
        cd /data/app/we-yan-agent/genie-client/ || { echo "Directory not found"; exit 1; }
        if [ ! -d ".venv" ]; then
            echo -e "${BLUE}创建Python虚拟环境...${NC}"
            uv sync
        fi
        source .venv/bin/activate
        nohup sh -c 'exec python server.py' genie-client >> $LOG_DIR/genie-client.log 2>&1 &
        echo "✅ MCP客户端启动成功 Log: $LOG_DIR/genie-client.log"
    fi
}

# 启动 genie-tool（8188）
start_tool() {
    local port=8188
    local file_path="/data/app/we-yan-agent/genie-tool/autobots.db"
    if is_port_in_use $port; then
        echo "Port $port is already in use. genie-tool may already be running."
    else
        # 检查虚拟环境
        cd /data/app/we-yan-agent/genie-tool/  || { echo "Directory not found"; exit 1; }
        if [ ! -d ".venv" ]; then
            echo -e "${BLUE}创建Python虚拟环境...${NC}"
            uv sync
        fi
        echo "Starting genie-tool on port $port..."
        source .venv/bin/activate
        # 判断文件是否存在
        if [ -f "$file_path" ]; then
            echo "$file_path sqlite已经存在"
        else
            echo -e "${BLUE}初始化数据库...${NC}"
            if python -m genie_tool.db.db_engine; then
                echo -e "${GREEN}✅ 数据库初始化成功${NC}"
            else
                echo -e "${RED}❌ 数据库初始化失败${NC}"
                cd ..
                return 1
            fi
        fi
        nohup sh -c 'exec python server.py' genie-tool >> $LOG_DIR/genie-tool.log 2>&1 &
        echo "✅ 工具启动成功 Log: $LOG_DIR/genie-tool.log"
    fi
}

# 启动 UI（3000）
start_ui() {
    local port=3000
    if is_port_in_use $port; then
        echo "Port $port is already in use. UI may already be running."
    else
        echo "Starting UI on port $port..."
        cd /data/app/we-yan-agent/ui || { echo "Directory not found"; exit 1; }
        pnpm install
        nohup pnpm run dev >> $LOG_DIR/ui.log 2>&1 &
        echo "✅ 前端启动成功 Log: $LOG_DIR/ui.log"
    fi
}

# 启动 genie-backend（8082）
start_backend() {
    local port=8082
    if is_port_in_use $port; then
        echo "Port $port is already in use. genie-backend may already be running."
    else
       #  后端构建
        echo -e "${BLUE}🔨 构建后端项目...${NC}"
        cd /data/app/we-yan-agent/genie-backend
        if sh build.sh; then
            echo -e "${GREEN}✅ 后端构建成功${NC}"
        else
            echo -e "${RED}❌ 后端构建失败${NC}"
            cd ..
            return 1
        fi
        echo "Starting genie-backend on port $port..."
        cd /data/app/we-yan-agent/genie-backend/ || { echo "Directory not found"; exit 1; }
        nohup java -classpath ./target/genie-backend/conf/:./target/genie-backend/lib/* \
            -Dbasedir=./target/genie-backend \
            -Dfile.encoding=UTF-8 \
            com.jd.genie.GenieApplication >> $LOG_DIR/genie-backend.log 2>&1 &
        echo "✅ 后端启动成功 Log: $LOG_DIR/genie-backend.log"
    fi
}

# 开始执行服务启动逻辑
echo "🚀 Starting services..."
start_client
start_tool
start_ui
start_backend
echo "✅ Services startup complete."
